import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
    private chooseType:any=3;
    private ctx:any;
    private r:any;
    private lastPoint:any;//链接的最终个数
    private arr:any;
    private restPoint:any;
    private pswObj:any;
    private width:any;
    private height:any;
    private touchFlag:any;
    private canvas:any;
    private message:any;

  constructor(public navCtrl: NavController) {
     
  }

  //页面初始化完后
  ionViewDidEnter() {  
    this.init();
  }

  // 初始化解锁密码面板
  drawCle(x, y) { 
            this.ctx.strokeStyle = '#a8c2d4';
            this.ctx.lineWidth = 4;
            this.ctx.beginPath();
            this.ctx.arc(x, y, this.r, 0, Math.PI * 2, true);
            this.ctx.closePath();
            this.ctx.stroke();
        }

 // 初始化圆心
  drawPoint() { 
            for (var i = 0 ; i < this.lastPoint.length ; i++) {
                this.ctx.fillStyle = '#a8c2d4';
                this.ctx.beginPath();
                this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2, 0, Math.PI * 2, true);
                this.ctx.closePath();
                this.ctx.fill();
            }
        }

    //报错的时候给圆心设置颜色
    drawPoint2(type) { 
            for (var i = 0 ; i < this.lastPoint.length ; i++) {
                this.ctx.fillStyle = type;
                this.ctx.beginPath();
                this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2, 0, Math.PI * 2, true);
                this.ctx.closePath();
                this.ctx.fill();
            }
        }

    // 初始化状态线条        
    drawStatusPoint(type) { 
            for (var i = 0 ; i < this.lastPoint.length ; i++) {
                this.ctx.strokeStyle = type;
                this.ctx.beginPath();
                this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r, 0, Math.PI * 2, true);
                this.ctx.closePath();
                this.ctx.stroke();
            }
        }

    // 解锁轨迹        
    drawLine(po, lastPoint) {
            this.ctx.beginPath();
            this.ctx.lineWidth = 5;
            this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);
            console.log(this.lastPoint.length);
            for (var i = 1 ; i < this.lastPoint.length ; i++) {
                this.ctx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
            }
            this.ctx.lineTo(po.x, po.y);
            this.ctx.stroke();
            this.ctx.closePath();

        }

    //解锁轨迹的颜色设置        
    drawLine2(lastPoint,type) {
            this.ctx.beginPath();
            this.ctx.lineWidth = 5;
            this.ctx.strokeStyle=type;
            this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);
            console.log(this.lastPoint.length);
            for (var i = 1 ; i < this.lastPoint.length ; i++) {
                this.ctx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
            }
            this.ctx.stroke();
            this.ctx.closePath();
        }

// 创建解锁点的坐标，根据canvas的大小来平均分配半径        
createCircle() {
            var n = this.chooseType;
            var count = 0;
            this.r = this.ctx.canvas.width / (2 + 4 * n);// 公式计算
            this.lastPoint = [];
            this.arr = [];
            this.restPoint = [];
            var r = this.r;
            for (var i = 0 ; i < n ; i++) {
                for (var j = 0 ; j < n ; j++) {
                    count++;
                    var obj = {
                        x: j * 4 * r + 3 * r,
                        y: i * 5 * r + 4 * r,
                        index: count
                    };
                    this.arr.push(obj);
                    this.restPoint.push(obj);
                }
            }

            this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
            for (var i = 0 ; i < this.arr.length ; i++) {
                this.drawCle(this.arr[i].x, this.arr[i].y);
            }
            //return arr;
        }

    // 获取touch点相对于canvas的坐标
    getPosition(e) {
            var rect = e.currentTarget.getBoundingClientRect();
            var po = {
                x: (e.touches[0].clientX - rect.left)*window.devicePixelRatio,
                y: (e.touches[0].clientY - rect.top)*window.devicePixelRatio
              };
            return po;
        }

    // 核心变换方法在touchmove时候调用
    update(po) {
            this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);

            for (var i = 0 ; i < this.arr.length ; i++) { // 每帧先把面板画出来
                this.drawCle(this.arr[i].x, this.arr[i].y);
            }

            this.drawPoint();// 每帧花轨迹
            this.drawLine(po , this.lastPoint);// 每帧画圆心

            for (var i = 0 ; i < this.restPoint.length ; i++) {
                if (Math.abs(po.x - this.restPoint[i].x) < this.r && Math.abs(po.y - this.restPoint[i].y) < this.r) {
                    this.drawPoint();
                    this.lastPoint.push(this.restPoint[i]);
                    this.restPoint.splice(i, 1);
                    break;
                }
            }

        }

     // 检测密码   
    checkPass(psw1, psw2) {
            var p1 = '',
            p2 = '';
            for (var i = 0 ; i < psw1.length ; i++) {
                p1 += psw1[i].index + psw1[i].index;
            }
            for (var i = 0 ; i < psw2.length ; i++) {
                p2 += psw2[i].index + psw2[i].index;
            }
            return p1 === p2;
        }

     // touchend结束之后对密码和状态的处理   
    storePass(psw,e) {
            //链接的点数小月两个不保存
            if(psw.length<3){
                this.message="链接数不能小于2位";
                return;
            }
            if (this.pswObj.step == 1) {
                if (this.checkPass(this.pswObj.fpassword, psw)) {
                    this.pswObj.step = 2;
                    this.pswObj.spassword = psw;
                    this.message="密码保存成功";
                    this.drawStatusPoint('#2CFF26');
                    this.drawPoint2('#2CFF26');
                     //设置线条的颜色
                   this.drawLine2(this.lastPoint,'#2CFF26');
                    window.localStorage.setItem('passwordxx', JSON.stringify(this.pswObj.spassword));
                    window.localStorage.setItem('chooseType', this.chooseType);
                } else {
                   this.message="两次不一致，重新输入";
                   //设置线条的颜色
                   this.ctx.strokeStyle='red';
                   this.drawStatusPoint('red');
                    delete this.pswObj.step;
                }
            } else if (this.pswObj.step == 2) {
                if (this.checkPass(this.pswObj.spassword, psw)) {
                    this.message="解锁成功";
                    this.drawStatusPoint('#2CFF26');
                    this.drawPoint2('#2CFF26');
                     //设置线条的颜色
                   this.drawLine2(this.lastPoint,'#2CFF26');
                } else {
                    this.drawStatusPoint('red');
                    //设置划线的额颜色
                    this.drawPoint2('red');
                     //设置线条的颜色
                   this.drawLine2(this.lastPoint,'red')
                   this.message="解锁失败";
                }
            } else {
                this.pswObj.step = 1;
                this.pswObj.fpassword = psw;
                this.message="再次输入";
            }

        }

    //初始化的时候判断是否是解锁       
    makeState() {
            if (this.pswObj.step == 2) {  
                this.message="请绘制手势密码";
            }
        }

        //初始化的个数
        setChooseType(type){
            this.chooseType = type;
            this.init();
        }

    //重置密码    
    updatePassword(){
            this.message="请设置手势密码";
            window.localStorage.removeItem('passwordxx');
            window.localStorage.removeItem('chooseType');
            this.pswObj = {};
            this.reset();
        }

    //初始化面板
    initDom(){
            var canvas = document.getElementsByName('canvas');
            var width = this.width || screen.availWidth;
            var height = this.height || screen.availHeight/1.5;
            // 高清屏锁放 canvas
            document.getElementsByName('canvas')[0].style.width = width + "px";
            document.getElementsByName('canvas')[0].style.height = height + "px";
            document.getElementsByName('canvas')[0]['height'] = height * window.devicePixelRatio;
            document.getElementsByName('canvas')[0]['width']= width * window.devicePixelRatio;

        }
    //初始化手势图       
    init() {
            this.initDom();
            this.pswObj = window.localStorage.getItem('passwordxx') ? {
                step: 2,
                spassword: JSON.parse(window.localStorage.getItem('passwordxx'))
            } : {};
            this.message =  window.localStorage.getItem('passwordxx')?'请绘制手势密码':'设置手势密码';
            this.lastPoint = [];
            this.makeState();
            this.touchFlag = false;
            this.canvas = document.getElementsByName('canvas');
            this.ctx = this.canvas[0].getContext('2d');
            this.createCircle();
            this.bindEvent();
        }
     //重置画版   
    reset() {
            //this.makeState();
            this.createCircle();
        }

    //绑定事件    
    bindEvent() {
                var self = this;
                this.canvas[0].addEventListener("touchstart", function (e) {
                    e.preventDefault();// 某些android 的 touchmove不宜触发 所以增加此行代码
                    var po = self.getPosition(e);
                    console.log(po);
                    for (var i = 0 ; i < self.arr.length ; i++) {
                        if (Math.abs(po.x - self.arr[i].x) < self.r && Math.abs(po.y - self.arr[i].y) < self.r) {

                            self.touchFlag = true;
                            self.drawPoint();
                            self.lastPoint.push(self.arr[i]);
                            self.restPoint.splice(i,1);
                            break;
                        }
                    }
                }, false);
                this.canvas[0].addEventListener("touchmove", function (e) {
                    if (self.touchFlag) {
                        self.update(self.getPosition(e));
                    }
                }, false);
                this.canvas[0].addEventListener("touchend", function (e) {
                    if (self.touchFlag) {
                        self.touchFlag = false;
                        self.storePass(self.lastPoint,e);
                        setTimeout(function(){
                            self.reset();
                        }, 300);
                    }

                }, false);
    }
}
